package zmee.sso;

import kd.bos.dc.api.model.Account;
import kd.bos.exception.KDException;
import kd.bos.exception.LoginErrorCode;
import kd.bos.login.thirdauth.app.AppAuthResult;
import kd.bos.login.thirdauth.app.ThirdAppAuthtication;
import kd.bos.login.thirdauth.app.UserType;
import kd.bos.util.ExceptionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.util.Properties;

/**
 * OA手机端认证
 * @uthor luozilong
 * @date 20230416
 */
public class OAMobSSO extends ThirdAppAuthtication {
    public Logger logger = LoggerFactory.getLogger(OAMobSSO.class);

    /**
     * 判断是否为移动版url
     * @return
     */
    @Override
    public boolean isNeedHandle(HttpServletRequest request, Account account) {
        boolean isNeed = false;
        String device = request.getParameter("device");
        if(StringUtils.isNotEmpty(device)&&device.equals("mob")){
            isNeed=true;
        }
        return isNeed;
    }




    /**
     * 用户登录验证
     * @param request
     * @param account
     * @return
     */
    @Override
    public AppAuthResult appAuthtication(HttpServletRequest request, Account account) {
        logger.info("请求(lxw)appurl:"+request.getRequestURL());

        //用户登录对象
        AppAuthResult result=new AppAuthResult();
        result.setSucceed(false);
        //用户名登录
        result.setUserType(UserType.USER_NAME);
        //oa发送的用户登录名
        String loginid=request.getParameter("loginid");
        //时间戳
        String stamp=request.getParameter("timestamp");
        //oa发送的验证token
        String token=request.getParameter("loginTokenFromThird");
        logger.info("loginid："+loginid);
        logger.info("timestamp："+stamp);
        logger.info("token："+token);
        //用户名，时间戳，token不为空时
        if(StringUtils.isNotEmpty(loginid)&&StringUtils.isNotEmpty(stamp)&&StringUtils.isNotEmpty(token)){
            try{
                //获取密钥
                String secret=getSecrete();
                //SH1算法拼接token
                String sha1Token=getTokenBySHA1(secret+loginid+stamp);
                //token一致验证通过
                logger.info("看看哪个插件先执行 (OAMobSSO)->appAuthtication sha1Token >>> "+sha1Token+"\ntoken >>> "+token);
//                if(token.equals(sha1Token)){
                    logger.info("（PLSSOServerPlugin）()getTrdSSOAuth()- loginid："+loginid);
                    result.setUserFlag(loginid);
                    result.setSucceed(true);
                    logger.info("（PLSSOServerPlugin）getTrdSSOAuth()- result设置成功："+result);
                    return result;
//                }
            }catch (Exception shaExp){
                logger.error(shaExp.getMessage());
                String sMsg = String.format("App验证错误: ", ExceptionUtils.getExceptionStackTraceMessage(shaExp));
                throw new KDException(LoginErrorCode.loginBizException, sMsg);


            }

        }
        return result;
    }
    /**
     * @Comment SHA1实现
     * @author liuxianwen
     * @return
     */
    public static String getTokenBySHA1(String inStr) throws Exception {
        MessageDigest sha = null;
        try {
            sha = MessageDigest.getInstance("SHA");
        } catch (Exception e) {
            System.out.println(e.toString());
            e.printStackTrace();
            return "";
        }

        byte[] byteArray = inStr.getBytes("UTF-8");
        byte[] md5Bytes = sha.digest(byteArray);
        StringBuffer hexValue = new StringBuffer();
        for (int i = 0; i < md5Bytes.length; i++) {
            int val = ((int) md5Bytes[i]) & 0xff;
            if (val < 16) {
                hexValue.append("0");
            }
            hexValue.append(Integer.toHexString(val));
        }
        return hexValue.toString();
    }
    //获取密钥
    public String getSecrete(){
        Properties properties = new Properties();
        String secret="";
        try {
//			InputStream in = this.getClass().getResourceAsStream("/sso.properties");
            InputStream in = this.getClass().getClassLoader().getResourceAsStream("resources/transferProp.properties");//resources
            properties.load(in);
            secret=properties.getProperty("secretkey");
            logger.info("kd.bos.exam.utils.PLSsoParam-secrete："+toString());
        } catch (IOException e) {
            e.printStackTrace();
            logger.error("kd.bos.exam.utils.PLSsoParam.setParam():"+e.toString());
        }
        return secret;
    }
}
